<?php
namespace app\supplyer\controller\sys_admin;

use app\AdminController;
use app\member\model\AccountModel;
use app\member\model\UsersModel;
use app\supplyer\Controller;
use app\supplyer\model\SupplyerModel;
use app\supplyer\model\SupplyerWithdrawModel;
use think\Db;

/**
 * 退货信息
 */
class Withdraw extends AdminController
{
    protected function initialize()
    {
        parent::initialize();
        $this->Model = new SupplyerWithdrawModel();
    }
	/*------------------------------------------------------ */
	//-- 首页
	/*------------------------------------------------------ */
    public function index()
    {
        $this->assign("start_date", date('Y/m/01',strtotime("-1 months")));
        $this->assign("end_date",date('Y/m/d'));
        $this->getList(true);
        $balance_money = (new SupplyerModel())->where('supplyer_id',$this->supplyer_id)->value('balance_money');
        $withdraw_money = $this->Model->where('supplyer_id',$this->supplyer_id)->where('status',0)->sum('money');
        $success_withdraw_money = $this->Model->where('supplyer_id',$this->supplyer_id)->where('status',9)->sum('money');
        $this->assign("balance_money",$balance_money);
        $this->assign("withdraw_money",$withdraw_money);
        $this->assign("success_withdraw_money",$success_withdraw_money);
        return $this->fetch('index');
    }
    /*------------------------------------------------------ */
    //-- 获取列表
    //-- $runData boolean 是否返回模板
    /*------------------------------------------------------ */
    public function getList($runData = false) {
        $this->userWithdrawType = $this->getDict('UserWithdrawType');
        $search['keyword'] = input('keyword','','trim');
        $search['status'] = input('status',0,'intval');
        $search['type'] = input('type','','trim');
        $reportrange = input('reportrange');
        $where = [];
//        if (empty($reportrange) == false){
//            $dtime = explode('-',$reportrange);
//            $where[] = ['add_time','between',[strtotime($dtime[0]),strtotime($dtime[1])+86399]];
//        }else{
//            $where[] = ['add_time','between',[strtotime("-1 months"),time()]];
//        }
//        if ($search['status'] >= 0){
//            $where[] = ['status','=',$search['status']];
//        }
//        if (empty($search['keyword']) == false){
//            $UsersModel = new UsersModel();
//            $uids = $UsersModel->where(" mobile LIKE '%".$search['keyword']."%' OR user_name LIKE '%".$search['keyword']."%' OR nick_name LIKE '%".$search['keyword']."%' OR user_id = '".$search['keyword']."'")->column('user_id');
//            $uids[] = -1;//增加这个为了以上查询为空时，限制本次主查询失效
//            $where[] = ['user_id','in',$uids];
//        }
        if (empty($search['type']) == false){
            $where[] = ['account_type','=',$search['type']];
        }
        $is_export =  input('is_export',0,'intval');
        if ($is_export > 0) {
            return $this->export($where);
        }
//        $viewObj = $this->Model->where($where);

        $sqlOrder = "add_time DESC";
        $data = $this->getPageList($this->Model,$where,'*',10,$sqlOrder);
        foreach ($data['list'] as $key=>$row){
            $row['account_info'] = json_decode($row['account_info'],true);
            $row['supplyer_name'] = Db::name('supplyer')->where(['supplyer_id' => $row['supplyer_id']])->value('company_name');
            $data['list'][$key] = $row;
        }
        $this->assign("status", $this->Model->status);
        $this->assign("search", $search);
        $this->assign("data", $data);
        $fee_types = config('config.fee_types');
        $this->assign('fee_types', $fee_types);
        $this->assign('withdraw_account_type', config('config.withdraw_account_type'));
        if ($runData == false){
            $data['content']= $this->fetch('list')->getContent();
            unset($data['list']);
            return $this->success('','',$data);
        }
        return true;
    }

    /*------------------------------------------------------ */
    //-- 信息页调用
    //-- $data array 自动读取对应的数据
    /*------------------------------------------------------ */
    public function asInfo($data){
        $data['account'] = json_decode($data['account_info'],true);
        $userWithdrawType = $this->getDict('UserWithdrawType');
        $data['status_name'] = $userWithdrawType[$data['status']]['name'];
        $data['supplyer_name'] = Db::name('supplyer')->where(['supplyer_id' => $data['supplyer_id']])->value('company_name');
        $this->assign('withdraw_account_type', config('config.withdraw_account_type'));
        $supplyer = (new SupplyerModel())->where('supplyer_id',$this->supplyer_id)->find();
        $this->assign('supplyer', $supplyer);
        return $data;
    }

    /*------------------------------------------------------ */
    //-- 修改前处理
    /*------------------------------------------------------ */
    public function beforeEdit($data){
        $operating = input('operating','note','trim');
        if ($operating == 'note'){
            if (empty($data['admin_note'])){
                return $this->error('请填写备注.');
            }
        }elseif ($operating == 'refuse'){
            if (empty($data['admin_note'])){
                return $this->error('请填写备注，列明拒绝原因.');
            }
            $data['status'] = 1;
            $data['refuse_time'] = time();
            $data['admin_id'] = AUID;
        }elseif ($operating == 'pay'){
            if (empty($data['pay_info'])){
                return $this->error('请填写打款信息.');
            }
            $data['status'] = 9;
            $data['complete_time'] = time();
            $data['admin_id'] = AUID;
        }else{
            return $this->error('非法操作.');
        }
        $data['update_time'] = time();
        Db::startTrans();//启动事务
        return $data;
    }
    /*------------------------------------------------------ */
    //-- 修改后处理
    /*------------------------------------------------------ */
    public function afterEdit($data){
        $info = $this->Model->find($data['log_id']);
        $AccountModel = new AccountModel();
        $RediLock="Supplyer_With_".$data['status']."_".$info['supplyer_id'].'_log_id_'.$info['log_id'];
        $res = redisLook($RediLock);
        if($res == false){
            return $this->error('请勿重复提交');
        }
        if ($data['status'] == 1){//拒绝提现，退回帐户
            $res = (new SupplyerModel())->where('supplyer_id',$info['supplyer_id'])->inc('balance_money',$info['money'])->update();
            if ($res === false) {
                redisLook($RediLock,-1);//销毁锁
                Db::rollback();// 回滚事务
                return $this->error('未知错误，提现退回商户余额失败.');
            }
        }
        redisLook($RediLock,-1);//销毁锁
        Db::commit();// 提交事务

        return $this->success('操作成功.','reload');
    }
}
